<template>
  <!-- 添加键盘事件 -->
  <div @keyup.enter="login">
    <NavBarBack title="登陆" />
    <!-- 输入框 -->
    <van-cell-group>
      <van-field
        v-model="username"
        required
        clearable
        label="用户名"
        right-icon="question-o"
        placeholder="请输入用户名"
        @click-right-icon="$toast('不许为空，且长度不小于2位')"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        required
      />
    </van-cell-group>
    <div style="text-align:center;margin-top:20px">
      <van-button round type="info" @click="login" style="width:80%"
        >登陆</van-button
      >
    </div>
  </div>
</template>

<script>
import NavBarBack from "../../components/navBarBack";
import { loginApi } from "../../api";
export default {
  name: "login",
  components: { NavBarBack },
  data() {
    return {
      username: "舒浩奇",
      password: "123456"
    };
  },
  methods: {
    // 判断用户名和密码
    login() {
      if (this.username === "" || this.username.length < 2) {
        this.$toast("账号不许为空，且长度不小2位！");
      } else if (this.password === "" || this.password.length < 6) {
        this.$toast("密码不许为空，且长度不小于6位！");
      } else {
        // 请求接口
        loginApi({ username: this.username, password: this.password }).then(
          res => {
            if (res.code === 1) {
              // 把数据存入vuex
              // console.log(this.$store)
              this.$store.commit("setUser", res.data);
              // 路由跳转
              this.$router.push("/user");
            } else {
              this.$toast(res.msg);
            }
          }
        );
        //
      }
    }
  }
};
</script>

<style></style>
